package Servlet;

import StudentDTO.UserCheckDTO;
import StudentDTO.UserInfoDTO;
import httpclient.MyPost;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import javax.json.bind.Jsonb;
import javax.json.bind.JsonbBuilder;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * @author 黄忠
 * 创建于2019-04-09
 */
@WebServlet(urlPatterns = {"/login/dgut"})
public class DgutServlet extends HttpServlet {

    protected void doGet(HttpServletRequest request,
                         HttpServletResponse response) throws IOException {

        // 告诉浏览器，响应数据的数据格式与字符编码。否则会乱码。
        response.setContentType("text/html;charset=UTF-8");

        Jsonb jsonb = JsonbBuilder.create();

        //信息核对
        String token=request.getParameter("token");
        List<NameValuePair> formparams = new ArrayList<>();
        formparams.add(new BasicNameValuePair("token", token));
        formparams.add(new BasicNameValuePair("appid", "javaee"));
        formparams.add(new BasicNameValuePair("appsecret", "b3b52e43ccfd"));
        formparams.add(new BasicNameValuePair("userip", "10.0.2.2"));
        String checkStr=MyPost.post("https://cas.dgut.edu.cn/ssoapi/v2/checkToken",formparams);
        UserCheckDTO ucd=jsonb.fromJson(checkStr, UserCheckDTO.class);
        if(ucd.getAccess_token()==null){
            System.out.println("核对失败！");
            response.sendRedirect("https://cas.dgut.edu.cn?appid=javaee");
        }
        System.out.println(jsonb.toJson(ucd));

        //获取用户信息
        formparams.clear();
        formparams.add(new BasicNameValuePair("access_token", ucd.getAccess_token()));
        formparams.add(new BasicNameValuePair("openid", ucd.getOpenid()));
        String inforStr= MyPost.post("https://cas.dgut.edu.cn/oauth/getUserInfo",formparams);
        UserInfoDTO uid=jsonb.fromJson(inforStr, UserInfoDTO.class);
        if(uid.getName()==null){
            System.out.println("验证失败！");
            response.sendRedirect("https://cas.dgut.edu.cn?appid=javaee");
        }
        System.out.println(jsonb.toJson(uid));

        HttpSession session = request.getSession(true);
        session.setAttribute("UserInfor",uid);
        response.sendRedirect("http://localhost:8080/HomePage.jsp");
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
        doGet(request,response);
    }
}